package com.vadmin.vadminjava.service;

import com.alibaba.fastjson.JSONObject;

import com.vadmin.vadminjava.common.ResultSetToJavaBean;
import com.vadmin.vadminjava.db.DBUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/******************************************************************************************
 *
 * 这个单独放权限管理、账号管理的东西
 *
 *****************************************************************************************/
@Component
public class AdminPermissionService {
	org.slf4j.Logger logger = LoggerFactory.getLogger(AdminPermissionService.class.getName());

	//管理账号列表
	public JSONObject adminList(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();
		//sql处理
		Integer page      = params.getInteger("page");
		Integer pageSize  = params.getInteger("pageSize");
		String  startTime = params.getString("startTime");
		String  endTime   = params.getString("endTime");

		//页码处理
		if(page==0 || pageSize==0){
			page = 1;
			pageSize = 100;
		}
		//条件处理
		String countSql = "SELECT COUNT(0) as count FROM admin_user WHERE 1=1 ";
		String sql =
				"SELECT u.*,ur.role_id,r.title" +
						" FROM admin_user u" +
						" LEFT JOIN auth_user_role ur on ur.user_id = u.id " +
						" LEFT JOIN auth_role r on r.id = ur.role_id" +
						" where 1=1  order by u.id";

		//if(StringUtils.nonEmptyString(startTime) && StringUtils.nonEmptyString(startTime)){
		//	sql += " AND create_time >= '" + startTime + "' ";
		//	countSql += " AND create_time >= '" + startTime + "' ";
		//}
		//if(StringUtils.nonEmptyString(endTime) && StringUtils.nonEmptyString(endTime)) {
		//	sql += " AND create_time <= '" + endTime + "' ";
		//	countSql += " AND create_time <= '" + endTime + "' ";
		//}

		sql += " limit " + ((page - 1) * pageSize) + "," + pageSize;
		//System.out.println(sql);
		//执行
		try {
			ArrayList<JSONObject> dataRows = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			int                   count   = ResultSetToJavaBean.copyJsonSingleQuery(dbUtil,countSql).getInteger("count");
			map.put("count",count);
			map.put("data", dataRows);
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}

	//角色列表
	public JSONObject roleList(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();
		//sql处理
		Integer page      = params.getInteger("page");
		Integer pageSize  = params.getInteger("pageSize");
		String  startTime = params.getString("startTime");
		String  endTime   = params.getString("endTime");

		//页码处理
		if(page==0 || pageSize==0){
			page = 1;
			pageSize = 100;
		}
		//条件处理
		String countSql = "SELECT COUNT(0) as count FROM auth_role WHERE 1=1 ";
		String sql = "SELECT * FROM auth_role where 1=1 ";

		//if(StringUtils.nonEmptyString(startTime) && StringUtils.nonEmptyString(startTime)){
		//	sql += " AND create_time >= '" + startTime + "' ";
		//	countSql += " AND create_time >= '" + startTime + "' ";
		//}
		//if(StringUtils.nonEmptyString(endTime) && StringUtils.nonEmptyString(endTime)) {
		//	sql += " AND create_time <= '" + endTime + "' ";
		//	countSql += " AND create_time <= '" + endTime + "' ";
		//}

		sql += " order by id ";
		sql += " limit " + ((page - 1) * pageSize) + "," + pageSize;

		//执行
		try {
			ArrayList<JSONObject> dataRows = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			int                   count   = ResultSetToJavaBean.copyJsonSingleQuery(dbUtil,countSql).getInteger("count");
			map.put("count",count);
			map.put("data", dataRows);
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}

	//角色创建
	public JSONObject roleAdd(JSONObject param) {
		DBUtil dbUtil = new DBUtil();
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		String title = param.getString("title");
		String sql = "";
		//执行
		try {

			//判断是否已经存在角色
			sql = "select * from auth_role where title='" + title + "'";
			ArrayList<JSONObject> dataRows = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			if(dataRows.size()>0){
				map.put("resultFlag", false);
				map.put("resultMsg", "操作失败，已经存在相同数据");
			}else{
				sql = "insert into auth_role(title)values('"+title+"')";
				dbUtil.insertOrUpdateInfoTONum(sql);
				map.put("resultFlag", true);
				map.put("resultMsg", "操作成功");
			}

		} catch (Exception e) {
			map.put("resultMsg", "操作失败: " + e.getMessage());
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}

	//用户角色修改
	public JSONObject userRoleEdit(JSONObject param) {
		DBUtil dbUtil = new DBUtil();
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);

		//参数处理
		Integer userId = param.getInteger("userId");
		Integer roleId = param.getInteger("roleId");
		if(userId== null || roleId == null){
			map.put("resultFlag", false);
			map.put("resultMsg", "缺少必要参数");
			return map;
		}

		String sql = "";
		//执行
		try {
			//删除旧权限
			sql = "DELETE from auth_user_role where user_id = " + userId;
			dbUtil.executeUpdateTOnum(sql);
			//插入
			sql = "insert into auth_user_role(user_id,role_id)values("+userId+","+roleId+")";
			//System.out.println(sql);
			dbUtil.insertOrUpdateInfoTONum(sql);
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");

		} catch (Exception e) {
			map.put("resultMsg", "操作失败: " + e.getMessage());
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}


	//菜单列表(用于修改权限时的那个数据)，目前这个设计只支持二级菜单,想要多级菜单？去食屎吧
	public JSONObject menuList(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();

		//用于最终输出的data
		ArrayList<JSONObject> data = new ArrayList<>();

		//执行
		try {
			//先找出一级菜单
			String sql = "SELECT * FROM auth_menu where parent_id = 0";
			ArrayList<JSONObject> dataRows = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			//遍历一级菜单数据
			for (JSONObject dataRow : dataRows) {
				Integer _parentId = dataRow.getInteger("id");//得到一级菜单id
				//找出这个一级菜单的二级菜单
				sql = "SELECT * FROM auth_menu where parent_id = " + _parentId;
				ArrayList<JSONObject> dataS = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
				dataRow.put("children", dataS);
				//放进最终的data
				data.add(dataRow);
			}
			map.put("data", data);
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}


	//角色的菜单列表
	public JSONObject roleMenuList(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();

		Integer roleId = params.getInteger("roleId");

		//执行
		try {
			String sql = "SELECT * FROM auth_role_pm where role_id = " + roleId;
			ArrayList<JSONObject> dataRows = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));

			map.put("data", dataRows);
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}


	//角色菜单更新
	public JSONObject roleMenuUpdate(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();

		Integer roleId = params.getInteger("roleId");
		String roleString = params.getString("roleString");

		//执行
		try {

			String sqlD = "delete from auth_role_pm where role_id=" + roleId;
			dbUtil.executeUpdateTOnum(sqlD);

			//如果有提交，就处理字符串，生成sql，并执行
			if(StringUtils.isNotEmpty(roleString)){
				String[] roleGroup = roleString.split("\\|");
				for (String s : roleGroup) {
					String[] _d = s.split("\\,");
					String sql = "insert into auth_role_pm(role_id,pm_id,pm_title)values("+roleId+","+_d[0]+",'"+_d[1]+"')";
					dbUtil.executeUpdate(sql);
				}
			}
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}


	//用户所属角色的权限
	public JSONObject userRolePermission(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();
		String sql = "";
		Integer userId = params.getInteger("userId");

		//用于最终输出的data
		ArrayList<JSONObject> data = new ArrayList<>();

		//执行
		try {
			//找到用户所属的角色的的权限数据
			sql = "select * from auth_user_role where user_id="+ userId;
			ArrayList<JSONObject> rs1 = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			Integer _roleId = rs1.get(0).getInteger("roleId");
			//System.out.println("用户的角色id是"+_roleId);

			//找到这个角色的所有权限
			sql = "select * from auth_role_pm where role_id=" + _roleId;
			ArrayList<JSONObject> rs2 = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			//System.out.println("这个角色的权限列表"+rs2);
			ArrayList<Integer> _rolePmArray = new ArrayList<>();//弄个list来放
			for (JSONObject o : rs2) {
				_rolePmArray.add(o.getInteger("pmId"));
			}
			//System.out.println("这个角色的权限列表2"+_rolePmArray);
			//System.out.println(_rolePmArray.contains(7));


			//找出所有一级菜单
			sql = "SELECT * FROM auth_menu where parent_id = 0 order by order_by desc,id asc";
			ArrayList<JSONObject> dataRows = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));
			//遍历一级菜单数据
			for (JSONObject dataRow : dataRows) {
				Integer _parentId = dataRow.getInteger("id");//得到一级菜单id

				//找出这个一级菜单的二级菜单
				sql = "SELECT * FROM auth_menu where parent_id = " + _parentId + "  order by order_by desc,id asc";
				ArrayList<JSONObject> dataS = ResultSetToJavaBean.copyJson(dbUtil.executeQuery(sql));

				//进行角色权限过滤,因为使用流的filter，返回的是一个List，最终的List里面还是JSONObject，照样使用
				List dataS2 = dataS.stream().filter(item -> _rolePmArray.contains(item.getInteger("id"))==true).collect(Collectors.toList());
				//System.out.println("进行filter的菜单："+dataS2);
				//如果这个二级菜单有数量
				if(dataS2.size()>0){
					dataRow.put("children", dataS2);
					//一级菜单，放进最终的data
					data.add(dataRow);
				}

			}
			map.put("data", data);
			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}


	//删除一级菜单（要找出一级菜单的所有二级菜单，与关联数据）
	public JSONObject menuDelOfLevel1(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();

		String id = params.getString("id");


		//执行
		try {

			//删除菜单表一级菜单
			String sql1 = "delete from auth_menu where id=" + id;
			dbUtil.executeUpdateTOnum(sql1);

			//删除角色菜单关联表
			String sqlPm = "delete from auth_role_pm where pm_id in (SELECT id from auth_menu where parent_id = "+id+")";
			dbUtil.executeUpdateTOnum(sqlPm);

			//删除二级菜单
			String sql3 = "delete from auth_menu where parent_id=" + id;
			dbUtil.executeUpdateTOnum(sql3);

			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}

	//删除二级菜单
	public JSONObject menuDelOfLevel2(JSONObject params) {
		JSONObject map = new JSONObject();
		map.put("resultFlag", false);
		DBUtil dbUtil = new DBUtil();

		String id = params.getString("id");


		//执行
		try {


			//删除菜单表数据
			String sqlM = "delete from auth_menu where id=" + id;
			dbUtil.executeUpdateTOnum(sqlM);

			//删除角色菜单关联表
			String sqlPm = "delete from auth_role_pm where pm_id=" + id;
			System.out.println(sqlPm);
			dbUtil.executeUpdateTOnum(sqlPm);

			map.put("resultFlag", true);
			map.put("resultMsg", "操作成功");
		} catch (Exception e) {
			map.put("resultMsg", "操作失败");
		} finally {
			dbUtil.closeNoErr();
		}
		return map;
	}
}
